package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.clientLossManagement.RemindTaskCreateDTO;
import com.pactera.madp.cp.api.dto.clientLossManagement.RemindTaskDTO;
import com.pactera.madp.cp.api.em.RemindTaskCronExpressionEnum;
import com.pactera.madp.cp.api.entity.BaseEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindCommunicationEntity;
import com.pactera.madp.cp.api.entity.clientLossManagement.RemindTaskRecordsEntity;
import com.pactera.madp.cp.api.feign.RemoteTaskService;
import com.pactera.madp.cp.mapper.clientLossManagement.RemindTaskRecordsMapper;
import com.pactera.madp.cp.service.IContactService;
import com.pactera.madp.cp.service.RemindCommunicationService;
import com.pactera.madp.cp.service.RemindTaskRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zkd
 * @date 2022/5/13 10:52
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class RemindTaskRecordsServiceImpl extends ServiceImpl<RemindTaskRecordsMapper,RemindTaskRecordsEntity> implements RemindTaskRecordsService {

    @Autowired
    private RemoteTaskService remoteTaskService;
    @Autowired
    private IContactService contactService;
    @Autowired
    private RemindCommunicationService remindCommunicationService;

    @Override
    public List<Integer> getRecordFinishedIdList() {
        List<Integer> ids = this.list(new LambdaQueryWrapper<RemindTaskRecordsEntity>()
                .eq(RemindTaskRecordsEntity::getIsFinished, "1"))
                .stream()
                .map(l -> l.getId()).collect(Collectors.toList());
        return ids;
    }

    @Override
    public R<Boolean> createTask(RemindTaskDTO dto) {
        List<RemindTaskRecordsEntity> remindTaskRecordsEntities = this.list(new LambdaQueryWrapper<RemindTaskRecordsEntity>()
                .eq(RemindTaskRecordsEntity::getWxUserId, dto.getWxUserId())
                .eq(RemindTaskRecordsEntity::getWxExternalUserid, dto.getWxExternalUserid()));
        for (RemindTaskRecordsEntity recordsEntity : remindTaskRecordsEntities) {
            if (recordsEntity.getIsFinished().equals("0")) {
                //为避免产生重复的成员未交流提醒定时任务,若存在未结束的记录则不新增该成员的未交流提醒任务
                return R.ok();
            }
        }

        List<RemindTaskRecordsEntity> collect = remindTaskRecordsEntities.stream()
                .filter(s -> s.getIsFinished().equals("1"))
                .collect(Collectors.toList());
        if (!collect.isEmpty()) {
            RemindTaskRecordsEntity recordsEntity = collect.stream().max(Comparator.comparing(l -> l.getCreateTime())).get();
            if (recordsEntity.getMsgTime().equals(dto.getMsgTime())) {
                //为避免产生重复的成员未交流提醒定时任务,若最后一次交流时间相等即该成员在提醒次数全部执行完毕后仍然与该客户是未交流状态，则不新增该成员的未交流提醒任务
                return R.ok();
            }
        }

        //保存未交流提醒任务记录
        RemindTaskRecordsEntity entity = new RemindTaskRecordsEntity();
        entity.setWxUserId(dto.getWxUserId());
        entity.setWxExternalUserid(dto.getWxExternalUserid());
        entity.setExecutedTimes(0);
        entity.setIsFinished("0");
        entity.setMsgTime(dto.getMsgTime());
        boolean success = this.save(entity);
        if (success) {
            RemindTaskRecordsEntity one = this.getOne(new LambdaQueryWrapper<RemindTaskRecordsEntity>()
                    .eq(RemindTaskRecordsEntity::getWxUserId, dto.getWxUserId())
                    .eq(RemindTaskRecordsEntity::getWxExternalUserid, dto.getWxExternalUserid())
                    .eq(RemindTaskRecordsEntity::getIsFinished,"0"));

            RemindTaskCreateDTO remindTaskCreateDTO = new RemindTaskCreateDTO();
            HashMap<String, Object> map = new HashMap<>();
            map.put("wxUserId",dto.getWxUserId());
            map.put("wxExternalUserid",dto.getWxExternalUserid());
            map.put("corpId",dto.getCorpId());
            String s = JSON.toJSONString(map);
            remindTaskCreateDTO.setMethodParamsValue(s);
            remindTaskCreateDTO.setCreateBy(dto.getWxUserId());
            remindTaskCreateDTO.setCreateTime(dto.getStartTime());
            remindTaskCreateDTO.setCronExpression(dto.getCronExpression());
            remindTaskCreateDTO.setStartTime(dto.getStartTime());
            remindTaskCreateDTO.setMethodName("sendNoCommunicationRemind");
            remindTaskCreateDTO.setJobTenantType("1");
            remindTaskCreateDTO.setJobType("2");
            remindTaskCreateDTO.setJobName("sendNoCommunicationRemind" + one.getId());
            remindTaskCreateDTO.setJobGroup("behaviorTrackTask");
            remindTaskCreateDTO.setClassName("noCommunicationRemindTask");
            remindTaskCreateDTO.setRemark("成员未交流提醒任务");
            remindTaskCreateDTO.setMisfirePolicy("3");
            return remoteTaskService.save(remindTaskCreateDTO, SecurityConstants.FROM_IN);
        } else {
            return R.failed("新增失败");
        }
    }

    @Override
    public void batchCreateTask(Integer corpId) {
        //检索消息存档获取未交流列表拿到wxUserId、wxExternalUserid集合
        List<Map<String, String>> noCommunicationMapList = contactService.getNoCommunicationMapList(corpId);
        log.info("noCommunicationMapList:{}",noCommunicationMapList);

        //获取未结束的提醒任务记录列表
        List<RemindTaskRecordsEntity> taskRecordsEntities = this.list(new LambdaQueryWrapper<RemindTaskRecordsEntity>()
                .eq(RemindTaskRecordsEntity::getIsFinished, "0"));
        ArrayList<RemindTaskRecordsEntity> common = new ArrayList<>();
        taskRecordsEntities.forEach(taskRecordsEntitie->{
            for (Map<String, String> noCommunicationMap : noCommunicationMapList) {
                if (taskRecordsEntitie.getWxExternalUserid().equals(noCommunicationMap.get("wxExternalUserid"))
                        && taskRecordsEntitie.getWxUserId().equals(noCommunicationMap.get("wxUserId"))) {
                    common.add(taskRecordsEntitie);
                }
            }
        });
        List<RemindTaskRecordsEntity> commonCollect = common.stream().distinct().collect(Collectors.toList());
        ArrayList<RemindTaskRecordsEntity> needToBeFinishedList = new ArrayList<>();
        taskRecordsEntities.removeAll(commonCollect);
        needToBeFinishedList.addAll(taskRecordsEntities);
        needToBeFinishedList.forEach(l->{
            //将不满足未交流的未交流提醒任务记录 置为结束状态
            l.setIsFinished("1");
        });
        if (!needToBeFinishedList.isEmpty()) {
            this.updateBatchById(needToBeFinishedList);
        }

        //未交流提醒配置
        RemindCommunicationEntity communicationEntity = remindCommunicationService.getOne(Wrappers.<RemindCommunicationEntity>lambdaQuery()
                .eq(RemindCommunicationEntity::getCorpId, corpId)
                .orderByDesc(BaseEntity::getCreateTime)
                .last("limit 1"));
        if (communicationEntity == null) {
            return;
        }
        noCommunicationMapList.forEach((Map<String, String> noCommunicationMap) ->{
            RemindTaskDTO dto = new RemindTaskDTO();
            dto.setCorpId(corpId);
            dto.setWxExternalUserid(noCommunicationMap.get("wxExternalUserid"));
            dto.setWxUserId(noCommunicationMap.get("wxUserId"));
            dto.setMsgTime(noCommunicationMap.get("msgTime"));
            String tomorrowDate = DateUtil.format(DateUtil.tomorrow(), "yyyy-MM-dd");
            LocalDateTime tomorrowDateTime = DateUtil.toLocalDateTime(DateUtil.parse(tomorrowDate + " 10:30:00"));
            dto.setStartTime(tomorrowDateTime);
            String frequency = communicationEntity.getFrequency();
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_ONE_HOUR.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_ONE_HOUR.getCronExpression());
            }
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_SIX_HOUR.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_SIX_HOUR.getCronExpression());
            }
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_ONE_DAY.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_ONE_DAY.getCronExpression());
            }
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_ONE_WEEK.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_ONE_WEEK.getCronExpression());
            }
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_TWO_WEEK.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_TWO_WEEK.getCronExpression());
            }
            if (frequency.equals(RemindTaskCronExpressionEnum.PER_ONE_MONTH.getCode())) {
                dto.setCronExpression(RemindTaskCronExpressionEnum.PER_ONE_MONTH.getCronExpression());
            }
            //创建成员未交流提醒定时任务
            createTask(dto);
        });
    }


}
